// 加载配置文件
var config = require('../config.js');
var ajaxSubmited = false;

function wxRequest(url = '', data = {}, fn, method = "POST", header = false) {

    var token = wx.getStorageSync('token');

    wx.request({
        url: config.API_HOST + url,
        method: method ? method : 'POST',
        data: data,
        header: header ? header : {
            "Content-Type": "application/json",
            "token": token,
        },
        success: function (res) {
            res = res.data;
            if (res.success) {
                fn(res.result);
            } else {
                if (res.code == -9000) {
                    wx.clearStorageSync();
                    getApp().getToken();
                }
                //生成订单报错的回调
                if (res.code == -9998) {
                    fn(res);
                }
                wx.showToast({
                    title: res.message,
                    icon: 'none'
                })
            }
        },
        fail: function (res) {
            // fn(res);
        }
    });
}

function wxRequestPro(url = '', data = {}, method = "GET",showToast=true, header = true) {
    return new Promise((resolve, reject) => {
        var headers={};
        headers["Content-Type"] =header ? "application/json" : "application/x-www-form-urlencoded"
        var token = wx.getStorageSync('token');
        if(token){
          headers['token'] = token;
        }
        wx.request({
            url: config.API_HOST + url,
            method: method,
            data: data,
            header: headers,
            success: function (res) {
              if(res.header.token) {
                wx.setStorageSync('token', res.header.token);
              }
              res = res.data;
              if(res.statusCode==401){
                wx.removeStorageSync('token');
                wx.removeStorageSync('phone');
                wx.removeStorageSync('openId');
                wx.removeStorageSync('room');
                wx.removeStorageSync('userMsg');
                wx.removeStorageSync('hasSub');
                // var userInfo=wx.getStorageSync('userInfo');
                // wx.clearStorageSync();
                // wx.setStorageSync('userInfo');
                wx.redirectTo({url:'/pages/bindLogin/main'})
              }
              else if(res.statusCode==200){
                resolve(res);
              }else {
                if (showToast && res.statusInfo) {
                  wx.showToast({
                      title: res.statusInfo,
                      icon: 'none'
                  })
                }
                reject(res)
              }
            },
            fail: function (res) {
              if(showToast){
                wx.showToast({
                    title: '网络异常',
                    icon: 'none'
                })
              }
                // reject(res);
            }
        });
    });
}

function uploadFile(src) {
    return new Promise((resolve, reject) => {
        var token = wx.getStorageSync('token');
        var url =config.API_HOST+'/UserServer/owner/info/uploadImg'
        wx.uploadFile({
          url: url,
          filePath: src,
          name: 'imgFile',
          header:{
            "Content-Type": "multipart/form-data",
            "token":token,
          },
          success(res){
            var res = JSON.parse(res.data);
            var param=res.param;
            resolve(param);
            var urlPath=param.url+param.filePath;
            console.warn('上传图片地址',urlPath);
          },
          fail(res){
            // reject(res);
            console.warn('fail=chooseImage',res)
            wx.showToast({
                title: "图片上传异常:"+res.statusInfo,
                icon: 'none'
            });
          },
          complete(res){
            console.warn('chooseImage',res)
          }
        })
    });
}

//--------------------通用方法--------------------------

//根据date格式化时间
function formatTime(date) {

    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();

    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
}

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

// 当前日期格式化 yyyy-MM-dd
function newDateFormat(value) {
    var date = value ? new Date(value.replace(/-/g, "/")) : new Date();
    var dateString = date.format("yyyy-MM-dd");
    return dateString;
}
// 当前日期格式化 yyyy-MM-dd
function newDateYearMonDa(value) {
    var date = value ? new Date(value.replace(/-/g, "/")) : new Date();
    var dateString = date.format("yyyy年MM月dd日");
    return dateString;
}

// 当前日期格式化 MM-dd hh:mm
function formatDayTime(value) {
    var date = value ? new Date(value.replace(/-/g, "/")) : new Date();
    var dateString = date.format("MM-dd hh:mm");
    return dateString;
}

// 当前日期格式化 yyyy-MM-dd hh:mm:ss
function formatYearDayTime(value) {
    var date = value ? new Date(value.replace(/-/g, "/")) : new Date();
    var dateString = date.format("yyyy-MM-dd hh:mm:ss");
    return dateString;
}

function formatNumber(n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
}

// 格式化时间戳
function getTime(timestamp) {
    var time = arguments[0] || 0;
    var t, y, m, d, h, i, s;
    t = time ? new Date(time) : new Date();
    y = t.getFullYear(); // 年
    m = t.getMonth() + 1; // 月
    d = t.getDate(); // 日

    h = t.getHours(); // 时
    i = t.getMinutes(); // 分
    s = t.getSeconds(); // 秒

    return [y, m, d].map(formatNumber).join('-') + ' ' + [h, i, s].map(formatNumber).join(':');

}

function getDateDiff(value) {
    // var value = '2020/06/11 08:45:00';
    // var value = '2020-05-06 14:45:00';
    // console.log(value);
    value = value.replace(/-/g, "/");

    var result = "";
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var week = day * 7;
    var month = day * 30;
    var timeDiff = new Date().getTime() - new Date(value).getTime();
    var t = new Date(value);
    var yearNow = t.getFullYear();
    var monthNow = t.getMonth() + 1;
    var datehNow = t.getDate();
    // console.log(timeDiff);
    if (timeDiff < minute) {
        result = "1" + "分钟前";
    } else if (timeDiff < hour) {
        result = "" + parseInt(timeDiff / minute) + "分钟前";
    } else if (timeDiff < day) {
        result = "" + parseInt(timeDiff / hour) + "小时前";
    } else if (timeDiff < month) {
        result = "" + parseInt(timeDiff / day) + "天前";
    } else {
        // result = "1" + "个月前";
        if (yearNow != new Date().getFullYear()) {
            result = yearNow + '-' + monthNow + '-' + datehNow;
        } else {
            result = monthNow + '月' + datehNow + '日';
        }

    }
    // console.log(result);
    return result;
}

function timeFormat(param) { //小于10的格式化函数
    return param < 10 ? '0' + param : param;
}

// 倒计时
function countDown(time, gapTime) {

    // 获取当前时间 gapTime: 本地时间与服务器时间差
    let newTime = gapTime ? new Date().getTime() - gapTime : new Date().getTime();
    // let newTime = new Date().getTime();

    // 对结束时间进行处理渲染到页面
    let endTime = new Date(time.replace(/-/g, "/")).getTime();
    let obj = null;

    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);

        obj = {
            day: timeFormat(day),
            hou: timeFormat(hou),
            min: timeFormat(min),
            sec: timeFormat(sec)
        }
    } else { //活动已结束，全部设置为'00'
        obj = {
            day: '00',
            hou: '00',
            min: '00',
            sec: '00'
        }
    }

    return obj;
}

// 检查手机号码
function checkPhoneNum(mobile) {
    if (mobile != '') {
        var tel = mobile; //获取手机号
        var telReg = !!tel.match(/^1[3456789]\d{9}$/);
        //如果手机号码不能通过验证
        if (!telReg) {
            wx.showToast({
                title: '请填写正确的手机号码',
                icon: 'none'
            })
            return false;
        }
        return true;
    } else {
        wx.showToast({
            title: '请填写手机号码',
            icon: 'none'
        })
        return false;
    }
}

// 检查身份证号码
function checkIDCardNum(idcard) {
    if (idcard != '') {
        var tel = idcard; //获取身份证号码
        var telReg = !!tel.match(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/);
        //如果身份证号码不能通过验证
        if (!telReg) {
            wx.showToast({
                title: '请填写正确的身份证号码',
                icon: 'none'
            })
            return false;
        }
        return true;
    } else {
        wx.showToast({
            title: '请填写身份证号码',
            icon: 'none'
        })
        return true;
    }
}

// 检查收货人
function checkShopName(name) {
    var self = this;
    if (name != '') {
        var tel = name; //获取身份证号码
        var telReg = !!tel.match(/^[\u4e00-\u9fa5_a-zA-Z0-9]{0,15}$/);
        //如果身份证号码不能通过验证
        if (telReg == false) {
            wx.showToast({
                title: '请输入长度不超过16的汉字、字母、数字',
                icon: 'none'
            })
            return true;
        }
        return false;
    } else {
        wx.showToast({
            title: '请输入收货人信息',
            icon: 'none'
        })
        return true;
    }
}

// 检查邮箱
function checkEmail(email) {
    var self = this;
    if (email != '') {
        var tel = email; //获取邮箱
        var telReg = !!tel.match(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/);
        //如果邮箱不能通过验证
        if (telReg == false) {
            wx.showToast({
                title: '请填写正确的邮箱',
                icon: 'none'
            })
            return true;
        }
        return false;
    } else {
        wx.showToast({
            title: '请填写邮箱',
            icon: 'none'
        })
        return true;
    }
}

// 获取格式化日期
function getFormatDate(str) {

    // 拆分日期为年 月 日
    var YEAR = str.substring(0, 4),
        MONTH = str.substring(4, 6),
        DATE = str.slice(-2);

    // 拼接为 2016/10/02 可用于请求日期格式
    var dateDay = YEAR + "/" + MONTH + "/" + DATE;

    // 获取星期几
    var week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
        day = new Date(dateDay).getDay();

    return {
        "dateDay": MONTH + "月" + DATE + "日 " + week[day]
    }

}


//对象深拷贝_json序列号
function jsonCopy(obj) {
    //转换成字符串再解析，就不会拷贝对应的地址指针
    var newArray = JSON.parse(JSON.stringify(obj));
    return newArray;
}

//对象深拷贝_for循环递归
function forCopy(obj) {
    function copy(obj) {
        var newobj = obj.constructor === Array ? [] : {};
        //判断是否是对象类型
        if (typeof obj !== 'object') {
            return;
        }
        //for...in遍历对象
        for (var i in obj) {
            // 判断当前i还是不是对象 ? 1遍历出来的还是个子对象，递归调用复制方法 : 2是基础类型，就直接赋值
            newobj[i] = typeof obj[i] === 'object' ? copy(obj[i]) : obj[i];
        }
        return newobj;
    }
    var copyArray = copy(obj)
    return copyArray;
}

// 判断两个对象属性值是否相等
function isObjectValueEqual(a, b) {
    //取对象a和b的属性名
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);

    //判断属性名的length是否一致
    if (aProps.length != bProps.length) {
        return false;
    }
    //循环取出属性名，再判断属性值是否一致
    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];

        if (a[propName] !== b[propName]) {
            return false;
        }
    }
    return true;
}

// 浮点型乘法
function accMul(a, b) {
    let c = 0
    let d = a.toString()
    let e = b.toString()
    try {
        c += a.toString().split('.')[1].length
    } catch (f) { }
    try {
        c += b.toString().split('.')[1].length
    } catch (f) { }
    return Number(d.replace('.', '')) * Number(e.replace('.', '')) / Math.pow(10, c)
}

Number.prototype.mul = function (arg) {
    return accMul(arg, this);
}

// 浮点型加法函数
function accAdd(arg1, arg2) {
    let r1, r2, m
    try {
        r1 = arg1.toString().split('.')[1].length
    } catch (e) {
        r1 = 0
    }
    try {
        r2 = arg2.toString().split('.')[1].length
    } catch (e) {
        r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2))
    return ((arg1 * m + arg2 * m) / m).toFixed(2)
}

// 金额补全两位小数
function formatAmount(value) {
    if (!value && value != 0)
        return;

    var formatValue = '',
        amount = value.toString().split(".");

    if (amount.length == 1) {
        formatValue = "¥ " + value.toString() + ".00";
        return formatValue;
    }

    if (amount.length > 1) {
        // 小数点1位追加一个0
        if (amount[1].length < 2) {
            formatValue = "¥ " + value.toString() + "0";
        }

        // 小数点2位以上截取2位
        if (amount[1].length >= 2) {
            formatValue = "¥ " + amount[0] + '.' + amount[1].substring(0, 2);
        }

        return formatValue;
    }
}

// 浮点数运算精度丢失，超过2位就保留2位小数，四舍五入 1 1.1 1.11
function formatAmountFixed(value) {

    var formatValue = '',
        amount = value.toString().split(".");

    formatValue = value;

    if (amount.length > 1) {
        // 超过2位就保留2位小数，四舍五入
        if (amount[1].length > 2) {
            formatValue = value.toFixed(2);
        }
    }
    return "¥" + formatValue;
}

// 金额补全两位小数_floor方式_不考虑四舍五入---不兼容浮动数，浮点数涉及到乘法运算，精度会丢失，
function formatAmountFloor(value) {
    // value=1234.1;//浮点数1234.1
    // 小数点2位以上截取2位
    var value = Math.floor(parseFloat(value) * 100) / 100;

    var formatValue = '',
        amount = value.toString().split(".");

    if (amount.length == 1) {
        formatValue = value.toString() + ".00";
    }

    if (amount.length > 1) {
        // 小数点1位追加一个0
        if (amount[1].length < 2) {
            formatValue = value.toString() + "0";
        }
    }
    return "¥" + formatValue;
}

// 金额补全两位小数无人民币符号
function formatAmountCount(value) {
    if (!value && value != 0)
        return;

    var formatValue = '',
        amount = value.toString().split(".");

    if (amount.length == 1) {
        formatValue = value.toString() + ".00";
        return formatValue;
    }

    if (amount.length > 1) {
        // 小数点1位追加一个0
        if (amount[1].length < 2) {
            formatValue = value.toString() + "0";
        }

        // 小数点2位以上截取2位
        if (amount[1].length >= 2) {
            formatValue = amount[0] + '.' + amount[1].substring(0, 2);
        }

        return formatValue;
    }
}

// 金额补全两位小数点 带正负显示
function formatAmountPositive(value) {
    if (!value && value != 0)
        return;

    var formatValueText = '',
        amount = value.toString().split(".");

    if (amount.length == 1) {
        if (value > 0) {
            formatValueText = "¥ +" + value.toString() + ".00";
        } else {
            formatValueText = "¥ " + value.toString() + ".00";
        }
    }

    if (amount.length > 1) {
        // 小数点1位追加一个0
        if (amount[1].length < 2) {
            if (value > 0) {
                formatValueText = "¥ +" + value.toString() + "0";
            } else {
                formatValueText = "¥ " + value.toString() + "0";
            }
        }

        // 小数点2位以上截取2位
        if (amount[1].length >= 2) {
            if (value > 0) {
                formatValueText = "¥ +" + amount[0] + '.' + amount[1].substring(0, 2);
            } else {
                formatValueText = "¥ " + amount[0] + '.' + amount[1].substring(0, 2);
            }
        }

    }

    return formatValueText;
}

// 分佣类型
function sellLvFilter(value) {
    if (!value)
        return null;

    var text = '';

    switch (parseInt(value)) {
        case 1:
            return "消费返利";
            break;
        case 2:
            return "销售提成";
            break;
        case 3:
            return "管理提成";
            break;
        case 4:
            return "分享提成"
            break;
    }

    return text;
}

//字段没有的显示为：暂无填写
function emptyCheck(value) {
    return value ? value : '暂无填写'
}

//小数转百分比
function toPercent(value) {
    return (value * 100).toFixed(0) + '%';
}

//2s内不变化才执行
function throttle(func, wait=2000) {
  let timeout
  return function () {
    let that = this
    let args = arguments

    if (!timeout) {
      timeout = setTimeout(function () {
        timeout = null
        func.apply(that, args)
      }, wait)
    }
  }
}

//setTimeout模拟interval
var timer = null;
function interval(func, wait=1000){
  let interv = function(){
      func.call(null);
      timer=setTimeout(interv, wait);
      return timer;
  };
  timer= setTimeout(interv, wait);
  return timer;
}
function clearInterval(){
  if (timer) {
    clearTimeout(timer);
    timer = null;
    //因为上面交替创建了两个timer
    //在第二个timer创建后，在它生效前移除延时任务
    setTimeout(()=>{
      clearTimeout(timer);
    }, 0);
  }
}

//函数节流_时间戳实现_避免2s内重复提交
var previous = '';
function tottleOne(func,delay=2000,funTip=()=>{}){
  var now = new Date();
  console.warn('now',now,previous,(now - previous))
  if (now - previous > delay) {
    previous = now;
    func.call(null);
  }else {
    funTip()
  }
}

//模仿 qs.stringify()
function stringifyQs(params={}) {
  return Object.keys(params).map(key => key + '=' + params[key]).join('&')
}

function getUserProfile() {
  var userInfo=wx.getStorageSync('userInfo')
  if(!userInfo){
    wx.getUserProfile({
      desc: '用于展示用户头像信息',
      success: (res) => {
        var userInfo = res.userInfo;
        wx.setStorageSync('userInfo',userInfo)
      },
      complete(res){
        console.warn('getUserProfile',res);
        wx.redirectTo({url: '/pages/bindLogin/main'})
      },
    })
  }else {
    wx.redirectTo({url: '/pages/bindLogin/main'})
  }
}

function socketTest(funTip=()=>{}) {
  var token=wx.getStorageSync('token');
  if(!token){
    return;
  }
  //先关闭之前的连接，进行新的连接
  wx.closeSocket()
  //本地服务器地址
  var wsApi = config.socket+"/smartWebsocket/"+token;
  //建立连接
  var SocketTask=wx.connectSocket({
    url: wsApi,
    header: {
     'content-type': 'application/json'
    },
    success: function () {
     console.warn("客户端连接成功！");
     wx.onSocketOpen(function(){
      console.warn('webSocket已打开！');
      var json={"event":"pong"}
      json=JSON.stringify(json)
      wx.onSocketMessage(function(msg){
        console.log('webSocket',msg);
        var message=JSON.parse(msg.data);
        var token=wx.getStorageSync('token');
        if(token){
          if(message.event=='ping') {
            //向服务器发送消息
            wx.sendSocketMessage({
             data: json
            })
            funTip(message.event)
          }
          if(message.lockStatus==1) {
            wx.showToast({
                title: '开门成功',
                icon: 'none'
            })
          }
          //二维码过期
          if(message.event=='ownerQrExpire') {
            console.warn('message.event',message.event)
            wx.setStorageSync('ownerQrExpire', true);
            funTip(message.event)
          }
        }

      })
      wx.sendSocketMessage({
       data: json
      })
     })
    }
  })

  SocketTask.onClose(function(res){
    console.warn('监听 WebSocket 连接关闭事件')
  })
}

module.exports = {
    config: config,
    wxRequest: wxRequest,
    wxRequestPro: wxRequestPro,
    uploadFile: uploadFile,
    checkPhoneNum: checkPhoneNum,
    checkIDCardNum: checkIDCardNum,
    checkShopName: checkShopName,
    checkEmail: checkEmail,
    formatTime: formatTime,
    formatDayTime: formatDayTime,
    formatYearDayTime: formatYearDayTime,
    getDateDiff: getDateDiff,
    getTime: getTime,
    countDown: countDown,
    getFormatDate: getFormatDate,
    newDateFormat: newDateFormat,
    newDateYearMonDa: newDateYearMonDa,
    jsonCopy: jsonCopy,
    forCopy: forCopy,
    isObjectValueEqual: isObjectValueEqual,

    formatAmount: formatAmount,
    formatAmountFixed: formatAmountFixed,
    formatAmountFloor: formatAmountFloor,
    formatAmountCount: formatAmountCount,
    formatAmountPositive: formatAmountPositive,
    sellLvFilter: sellLvFilter,
    emptyCheck: emptyCheck,
    toPercent: toPercent,
    throttle: throttle,
    interval: interval,
    clearInterval: clearInterval,
    tottleOne: tottleOne,
    stringifyQs: stringifyQs,
    getUserProfile: getUserProfile,
    socketTest: socketTest,
}
